package ag.script.project.standard.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.util.List;
import java.util.Map;

public class ScriptProjectXmlsTranslator {

    private final String projectPath;
    private final ScriptProjectStandardLog log;

    public ScriptProjectXmlsTranslator(String projectPath) {
        this.projectPath = projectPath;
        this.log = new ScriptProjectStandardLog(projectPath);
    }

    public void start() {
        log.log("【转移xml资源】");
        ScriptXmlPathScanner scriptImgPathScanner = new ScriptXmlPathScanner(projectPath);

        Map<File, List<ScriptResPaths>> scriptXmlPathMap = scriptImgPathScanner.start();
        for (File codeFile : scriptXmlPathMap.keySet()) {
            //代码路径
            log.log("代码路径", codeFile.getAbsolutePath());
            String jsCode = FileUtil.readUtf8String(codeFile);
            boolean jsCodeChanged = false;
            List<ScriptResPaths> scriptResPaths = scriptXmlPathMap.get(codeFile);
            for (ScriptResPaths scriptImgPath : scriptResPaths) {
                log.log("解析路径", scriptImgPath);
                //下面操作转移资源并且格式化代码
                String windowsPath = scriptImgPath.getWindowsPath();
                String windowsDestPath = scriptImgPath.getWindowsDestPath();
                if (FileUtil.exist(windowsPath)) {
                    if (!StrUtil.equals(windowsPath, windowsDestPath)) {
                        FileUtil.copy(windowsPath, windowsDestPath, true);
                    }
                } else {
                    log.log("文件不存在", windowsPath, "\n\t脚本:" + codeFile.getAbsolutePath(), "\n\t原路径:" + scriptImgPath.getOriginalPath());
                    continue;
                }

                //获取安卓路径和原始路径
                //如果安卓路径和原始路径相同，则跳过
                String androidPath = scriptImgPath.getAndroidPath();
                String originalPath = scriptImgPath.getOriginalPath();
                if (StrUtil.equals(androidPath, originalPath)) {
                    continue;
                }
                jsCode = StrUtil.replace(jsCode, originalPath, androidPath);
                jsCodeChanged = true;
            }
            if (jsCodeChanged) {
                //写入并且保存代码
                FileUtil.writeUtf8String(jsCode, codeFile);
            }
        }
    }

}
